<template>
  <div class="h-full">
    <n-space vertical>
      <n-card class="shadow-sm rounded-4px h-68px">
        <n-form class="w-full" size="small" inline>
          <n-form-item label="日期:" label-placement="left">
            <n-date-picker
              v-model:value="range"
              type="datetimerange"
              clearable
              :default-time="['00:00:00', '00:00:00']"
            />
          </n-form-item>
          <n-form-item label="车间:" label-placement="left" style="width: 200px">
            <n-select
              v-model:value="selectedAreas"
              clearable
              multiple
              label-field="areaname"
              value-field="areaname"
              :options="areas"
            />
          </n-form-item>

          <n-form-item label="" label-placement="left">
            <n-button type="primary" :on-click="getMaterialUsege">
              <template #icon><icon-mdi-map-search-outline /></template>
              查询
            </n-button>
          </n-form-item>
        </n-form>
      </n-card>
      <n-card class="rounded-4px shadow-sm">
        <n-space vertical>
          <vxe-grid v-bind="materialR01TotalOptions">
            <template #top>
              <div style="font-weight: 500; font-size: 28px">晶片利用率</div>
            </template>
          </vxe-grid>
          <vxe-grid v-bind="materialR04TotalOptions">
            <template #top>
              <div style="font-weight: 500; font-size: 28px">基座利用率</div>
            </template>
          </vxe-grid>

          <vxe-grid v-bind="materialR08TotalOptions">
            <template #top>
              <div style="font-weight: 500; font-size: 28px">上盖利用率</div>
            </template>
          </vxe-grid>
          <vxe-grid v-bind="materialR51TotalOptions">
            <template #top>
              <div style="font-weight: 500; font-size: 28px">IC利用率</div>
            </template>
          </vxe-grid>
        </n-space>
      </n-card>
    </n-space>
    <n-modal v-model:show="showModal">
      <n-card style="width: 1200px" :bordered="false" size="huge" role="dialog" aria-modal="true">
        <vxe-grid v-if="selectedStep == 'R01'" v-bind="materialR01Options">
          <template #top>
            <div style="font-weight: 500; font-size: 28px">晶片利用率</div>
          </template>
        </vxe-grid>
        <vxe-grid v-if="selectedStep == 'R04'" v-bind="materialR04Options">
          <template #top>
            <div style="font-weight: 500; font-size: 28px">基座利用率</div>
          </template>
        </vxe-grid>
        <vxe-grid v-if="selectedStep == 'R08'" v-bind="materialR08Options">
          <template #top>
            <div style="font-weight: 500; font-size: 28px">上盖利用率</div>
          </template>
        </vxe-grid>
        <vxe-grid v-if="selectedStep == 'R51'" v-bind="materialR51Options">
          <template #top>
            <div style="font-weight: 500; font-size: 28px">IC利用率</div>
          </template>
        </vxe-grid>
      </n-card>
    </n-modal>
  </div>
</template>

<script setup lang="tsx">
import { onMounted, reactive, ref } from 'vue';
import dayjs from 'dayjs';
import type { VxeGridProps } from 'vxe-table';
import { fetchAreaList, fetchMaterialTotalUsege, fetchMaterialUsege } from '@/service/api';

const range = ref<[number, number]>([dayjs().startOf('month').valueOf(), Date.now()]);

const areas = ref<Factory.Area[]>([]);
const selectedAreas = ref([]);
const showModal = ref(false);
const selectedStep = ref('');
const sumNum = (list: any[], field: string) => {
  let count = 0;
  list.forEach(item => {
    count += Number(item[field]);
  });
  return count;
};

const yieldNum = (list: any[], _field: string) => {
  let totalOut = 0;
  let totalPro = 0;
  let totalReturn = 0;
  list.forEach(item => {
    totalOut += Number(item.MATERIALOUT);
    totalPro += Number(item.TRACKOUT);
    totalReturn += Number(item.MATERIALRETURN);
  });
  if (totalOut - totalReturn !== 0) {
    return `${((totalPro / (totalOut - totalReturn)) * 100).toFixed(2)}%`;
  }
  return `${0}%`;
};

const materialR01TotalOptions = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  showFooter: true,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'AREA',
      title: '车间',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' },
      slots: {
        // 使用 JSX 渲染
        default: ({ row }) => {
          return [
            row.AREA !== ' ' ? (
              // eslint-disable-next-line @typescript-eslint/no-use-before-define
              <span style="color: blue" onClick={() => showDetailEvent(row, 'R01')}>
                {row.AREA}
              </span>
            ) : (
              row.AREA
            )
          ];
        }
      }
    },
    {
      field: 'MATERIALOUT',
      title: '发放数量'
    },
    {
      field: 'TRACKOUT',
      title: '上片产量'
    },
    {
      field: 'MATERIALRETURN',
      title: '退料数量'
    },
    {
      field: 'MATERIALUSGE',
      title: '晶片利用率'
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (columnIndex > 0 && columnIndex < 4) {
          return sumNum(data, column.property);
        }
        if (columnIndex === columns.length - 1) {
          return yieldNum(data, column.property);
        }
        return '';
      })
    ];
  },
  mergeCells: [],
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

const materialR04TotalOptions = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  showFooter: true,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'AREA',
      title: '车间',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' },
      slots: {
        // 使用 JSX 渲染
        default: ({ row }) => {
          return [
            row.AREA !== ' ' ? (
              // eslint-disable-next-line @typescript-eslint/no-use-before-define
              <span style="color: blue" onClick={() => showDetailEvent(row, 'R04')}>
                {row.AREA}
              </span>
            ) : (
              row.AREA
            )
          ];
        }
      }
    },
    {
      field: 'MATERIALOUT',
      title: '发放数量'
    },
    {
      field: 'TRACKOUT',
      title: '点胶产量'
    },
    {
      field: 'MATERIALRETURN',
      title: '退料数量'
    },
    {
      field: 'MATERIALUSGE',
      title: '基座利用率'
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (columnIndex > 0 && columnIndex < 4) {
          return sumNum(data, column.property);
        }
        if (columnIndex === columns.length - 1) {
          return yieldNum(data, column.property);
        }
        return '';
      })
    ];
  },
  mergeCells: [],
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

const materialR08TotalOptions = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  showFooter: true,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'AREA',
      title: '车间',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' },
      slots: {
        // 使用 JSX 渲染
        default: ({ row }) => {
          return [
            row.AREA !== ' ' ? (
              // eslint-disable-next-line @typescript-eslint/no-use-before-define
              <span style="color: blue" onClick={() => showDetailEvent(row, 'R08')}>
                {row.AREA}
              </span>
            ) : (
              row.AREA
            )
          ];
        }
      }
    },
    {
      field: 'MATERIALOUT',
      title: '发放数量'
    },
    {
      field: 'TRACKOUT',
      title: '封焊产量'
    },
    {
      field: 'MATERIALRETURN',
      title: '退料数量'
    },
    {
      field: 'MATERIALUSGE',
      title: '上盖利用率'
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (columnIndex > 0 && columnIndex < 4) {
          return sumNum(data, column.property);
        }
        if (columnIndex === columns.length - 1) {
          return yieldNum(data, column.property);
        }
        return '';
      })
    ];
  },
  mergeCells: [],
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

const materialR51TotalOptions = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  showFooter: true,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'AREA',
      title: '车间',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' },
      slots: {
        // 使用 JSX 渲染
        default: ({ row }) => {
          return [
            row.AREA !== ' ' ? (
              // eslint-disable-next-line @typescript-eslint/no-use-before-define
              <span style="color: blue" onClick={() => showDetailEvent(row, 'R51')}>
                {row.AREA}
              </span>
            ) : (
              row.AREA
            )
          ];
        }
      }
    },
    {
      field: 'MATERIALOUT',
      title: '发放数量'
    },
    {
      field: 'TRACKOUT',
      title: '固晶产量'
    },
    {
      field: 'MATERIALRETURN',
      title: '退料数量'
    },
    {
      field: 'MATERIALUSGE',
      title: 'IC利用率'
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (columnIndex > 0 && columnIndex < 4) {
          return sumNum(data, column.property);
        }
        if (columnIndex === columns.length - 1) {
          return yieldNum(data, column.property);
        }
        return '';
      })
    ];
  },
  mergeCells: [],
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

const materialR04Options = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  showFooter: true,
  // height: 500,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'AREA',
      title: '车间',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MODELTYPE',
      title: '型号',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'USERNAME',
      title: '员工',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MATERIALOUT',
      title: '发放数量'
    },
    {
      field: 'TRACKOUT',
      title: '点胶产量'
    },
    {
      field: 'MATERIALRETURN',
      title: '退料数量'
    },
    {
      field: 'MATERIALUSGE',
      title: '基座利用率'
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (columnIndex > 2 && columnIndex < 6) {
          return sumNum(data, column.property);
        }
        if (columnIndex === columns.length - 1) {
          return yieldNum(data, column.property);
        }
        return '';
      })
    ];
  },
  mergeCells: [],
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

const materialR08Options = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  showFooter: true,
  // height: 500,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'AREA',
      title: '车间',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MODELTYPE',
      title: '型号',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'USERNAME',
      title: '员工',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MATERIALOUT',
      title: '发放数量'
    },
    {
      field: 'TRACKOUT',
      title: '封焊产量'
    },
    {
      field: 'MATERIALRETURN',
      title: '退料数量'
    },
    {
      field: 'MATERIALUSGE',
      title: '上盖利用率'
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (columnIndex > 2 && columnIndex < 6) {
          return sumNum(data, column.property);
        }
        if (columnIndex === columns.length - 1) {
          return yieldNum(data, column.property);
        }
        return '';
      })
    ];
  },
  mergeCells: [],
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

const materialR01Options = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  showFooter: true,
  // height: 500,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'AREA',
      title: '车间',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MODELTYPE',
      title: '型号',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'USERNAME',
      title: '员工',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MATERIALOUT',
      title: '发放数量'
    },
    {
      field: 'TRACKOUT',
      title: '上片产量'
    },
    {
      field: 'MATERIALRETURN',
      title: '退料数量'
    },
    {
      field: 'MATERIALUSGE',
      title: '晶片利用率'
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (columnIndex > 2 && columnIndex < 6) {
          return sumNum(data, column.property);
        }
        if (columnIndex === columns.length - 1) {
          return yieldNum(data, column.property);
        }
        return '';
      })
    ];
  },
  mergeCells: [],
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

const materialR51Options = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  showFooter: true,
  // height: 500,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'AREA',
      title: '车间',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MODELTYPE',
      title: '型号',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'USERNAME',
      title: '员工',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MATERIALOUT',
      title: '发放数量'
    },
    {
      field: 'TRACKOUT',
      title: '上片产量'
    },
    {
      field: 'MATERIALRETURN',
      title: '退料数量'
    },
    {
      field: 'MATERIALUSGE',
      title: '晶片利用率'
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (columnIndex > 2 && columnIndex < 6) {
          return sumNum(data, column.property);
        }
        if (columnIndex === columns.length - 1) {
          return yieldNum(data, column.property);
        }
        return '';
      })
    ];
  },
  mergeCells: [],
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

const getMaterialUsege = async () => {
  const result = await fetchMaterialTotalUsege(
    dayjs(range.value[0]).format('YYYYMMDDHHmmss'),
    dayjs(range.value[1]).format('YYYYMMDDHHmmss'),
    selectedAreas.value.join(','),
    'R01'
  );
  if (result.data) {
    result.data.forEach(element => {
      if (element.MATERIALOUT - element.MATERIALRETURN !== 0) {
        // eslint-disable-next-line no-param-reassign
        element.MATERIALUSGE = `${((element.TRACKOUT / (element.MATERIALOUT - element.MATERIALRETURN)) * 100).toFixed(
          2
        )}%`;
      } else {
        // eslint-disable-next-line no-param-reassign
        element.MATERIALUSGE = '0%';
      }
    });
    materialR01TotalOptions.data = result.data;
  }

  const result04 = await fetchMaterialTotalUsege(
    dayjs(range.value[0]).format('YYYYMMDDHHmmss'),
    dayjs(range.value[1]).format('YYYYMMDDHHmmss'),
    selectedAreas.value.join(','),
    'R04'
  );
  if (result04.data) {
    result04.data.forEach(element => {
      if (element.MATERIALOUT - element.MATERIALRETURN !== 0) {
        // eslint-disable-next-line no-param-reassign
        element.MATERIALUSGE = `${((element.TRACKOUT / (element.MATERIALOUT - element.MATERIALRETURN)) * 100).toFixed(
          2
        )}%`;
      } else {
        // eslint-disable-next-line no-param-reassign
        element.MATERIALUSGE = '0%';
      }
    });
    materialR04TotalOptions.data = result04.data;
  }

  const result08 = await fetchMaterialTotalUsege(
    dayjs(range.value[0]).format('YYYYMMDDHHmmss'),
    dayjs(range.value[1]).format('YYYYMMDDHHmmss'),
    selectedAreas.value.join(','),
    'R08'
  );
  if (result08.data) {
    result08.data.forEach(element => {
      if (element.MATERIALOUT - element.MATERIALRETURN !== 0) {
        // eslint-disable-next-line no-param-reassign
        element.MATERIALUSGE = `${((element.TRACKOUT / (element.MATERIALOUT - element.MATERIALRETURN)) * 100).toFixed(
          2
        )}%`;
      } else {
        // eslint-disable-next-line no-param-reassign
        element.MATERIALUSGE = '0%';
      }
    });
    materialR08TotalOptions.data = result08.data;
  }

  const result51 = await fetchMaterialTotalUsege(
    dayjs(range.value[0]).format('YYYYMMDDHHmmss'),
    dayjs(range.value[1]).format('YYYYMMDDHHmmss'),
    selectedAreas.value.join(','),
    'R51'
  );
  if (result51.data) {
    result51.data.forEach(element => {
      if (element.MATERIALOUT - element.MATERIALRETURN !== 0) {
        // eslint-disable-next-line no-param-reassign
        element.MATERIALUSGE = `${((element.TRACKOUT / (element.MATERIALOUT - element.MATERIALRETURN)) * 100).toFixed(
          2
        )}%`;
      } else {
        // eslint-disable-next-line no-param-reassign
        element.MATERIALUSGE = '0%';
      }
    });
    materialR51TotalOptions.data = result51.data;
  }
};

const getAreaList = async () => {
  const result = await fetchAreaList();
  if (result.data) {
    areas.value = result.data;
  }
};

const showDetailEvent = async (row: any, opreation: string) => {
  showModal.value = true;
  selectedStep.value = opreation;
  const result = await fetchMaterialUsege(
    dayjs(range.value[0]).format('YYYYMMDDHHmmss'),
    dayjs(range.value[1]).format('YYYYMMDDHHmmss'),
    row.AREA,
    opreation
  );
  if (result.data) {
    result.data.forEach(element => {
      if (element.MATERIALOUT - element.MATERIALRETURN !== 0) {
        // eslint-disable-next-line no-param-reassign
        element.MATERIALUSGE = `${((element.TRACKOUT / (element.MATERIALOUT - element.MATERIALRETURN)) * 100).toFixed(
          2
        )}%`;
      } else {
        // eslint-disable-next-line no-param-reassign
        element.MATERIALUSGE = '0%';
      }
    });
    if (opreation === 'R01') {
      materialR01Options.data = result.data;
    }
    if (opreation === 'R04') {
      materialR04Options.data = result.data;
    }
    if (opreation === 'R08') {
      materialR08Options.data = result.data;
    }
    if (opreation === 'R51') {
      materialR51Options.data = result.data;
    }
  }
};

onMounted(async () => {
  getAreaList();
});
</script>
<style scoped></style>
